package sojo.com.inverter.controller;

import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sojo.com.inverter.utils.MyTcpListener;

import javax.websocket.server.PathParam;

/**
 * @author cheng_hu
 * @description: 语义模型API
 * @date 2022-08-15 21:23:04
 */
@Slf4j
@RestController
@RequestMapping("/v1")
public class SemanticController {

    private static MyTcpListener tcpListener = null;

    static {

        try {
            IpParameters params = new IpParameters();
            params.setHost("127.0.0.1");
            params.setPort(8020);
            // true RTU false TCP
            params.setEncapsulated(false);
            tcpListener = new MyTcpListener(params);
            //设置超时时间
            tcpListener.setTimeout(2000);
            //设置重连次数
            tcpListener.setRetries(3);
            //初始化
            tcpListener.init();

        } catch (Exception e) {
            e.printStackTrace();
            tcpListener = null;
        }
    }

    @GetMapping(value = "/test")
    public ResponseEntity<String> semanticList(@RequestParam("key") int key) {
        try {
            ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(1, 0, 2);
            tcpListener.send(request, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok("OK");
    }

}
